package com.qf.service.serviceImpl;

import com.qf.dao.UserRepository;
import com.qf.pojo.BaseResp;
import com.qf.pojo.User;
import com.qf.pojo.UserReq;
import com.qf.dao.UserMapper;
import com.qf.pojo.BaseResp;
import com.qf.pojo.User;
import com.qf.service.SendPhone;
import com.qf.service.UserService;
import com.qf.utils.JwtUtils;
import com.qf.utils.MyJia;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    SendPhone sendPhone;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    UserMapper userMapper;

    @Override
    public BaseResp registry(UserReq userReq, HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        User user = userRepository.findByName(userReq.getName());
        List<User> users = userRepository.findAll();
        if(StringUtils.isEmpty(userReq.getName())){
            baseResp.setCode(201);
            baseResp.setMgs("用户名不能为空");
            return baseResp;
        }
        if(StringUtils.isEmpty(userReq.getEmail())){
            baseResp.setCode(202);
            baseResp.setMgs("邮箱不能为空");
            return baseResp;
        }
        if(StringUtils.isEmpty(userReq.getPassword())){
            baseResp.setCode(203);
            baseResp.setMgs("密码不能为空");
            return baseResp;
        }
        if(user != null){
            baseResp.setCode(204);
            baseResp.setMgs("用户名已存在");
            return baseResp;
        }
        for (User user1: users
             ) {
            if(user1.getEmail().equals(userReq.getEmail())){
                baseResp.setCode(205);
                baseResp.setMgs("邮箱已被用");
                return baseResp;
            }

        }
        HttpSession session = request.getSession();
        Object object = session.getAttribute("email");
        if(object == null){
            baseResp.setCode(206);
            baseResp.setMgs("验证码为空");
            return baseResp;
        }
        if(!object.equals(userReq.getCode())){
            baseResp.setCode(207);
            baseResp.setMgs("验证码错误");
            return baseResp;
        }
        User user2 = new User();
        String password = MyJia.jiami(userReq.getPassword());
        userReq.setPassword(password);
        BeanUtils.copyProperties(userReq,user2);
        userRepository.saveAndFlush(user2);
        baseResp.setCode(200);
        baseResp.setMgs("注册成功");
        return baseResp;
    }

    @Override
    public BaseResp sendEmail(String email, HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        User user = userRepository.findByEmail(email);
        if(StringUtils.isEmpty(email)){
            baseResp.setCode(201);
            baseResp.setMgs("邮箱为空");
            return baseResp;
        }
        if(user != null){
            baseResp.setCode(202);
            baseResp.setMgs("邮箱已被用");
            return baseResp;
        }
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;
        try{
            mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setSubject("注册验证码");

            Random random = new Random();
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0;i<4;i++){
                stringBuffer.append(random.nextInt(10));
            }
            mimeMessageHelper.setText("<font style='color:red'>注册验证码为：</font>"+stringBuffer.toString(),true);
            javaMailSender.send(mimeMessage);
            HttpSession session = request.getSession();
            session.setAttribute("email",stringBuffer.toString());
            baseResp.setCode(200);
            baseResp.setMgs("邮件发送成功");
        }catch (Exception e){
            e.printStackTrace();
            baseResp.setCode(203);
            baseResp.setMgs("邮件发送失败");
        }
        return baseResp;
    }

    @Override
    public BaseResp updateemail(String email, HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;
        try{
            mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setSubject("注册验证码");

            Random random = new Random();
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0;i<4;i++){
                stringBuffer.append(random.nextInt(10));
            }
            mimeMessageHelper.setText("<font style='color:red'>注册验证码为：</font>"+stringBuffer.toString(),true);
            javaMailSender.send(mimeMessage);
            HttpSession session = request.getSession();
            session.setAttribute("updateemail",stringBuffer.toString());
            baseResp.setCode(200);
            baseResp.setMgs("邮件发送成功");

        }catch (Exception e){
            e.printStackTrace();
            baseResp.setCode(203);
            baseResp.setMgs("邮件发送失败");
        }
        return baseResp;
    }

    @Override
    public BaseResp login(User user) {
        BaseResp baseResp = new BaseResp();
        User user1 = userRepository.findByNameOrEmail(user.getName(), user.getName());
        String password = MyJia.jiami(user.getPassword());
        user.setPassword(password);
        if(StringUtils.isEmpty(user.getName())){
            baseResp.setCode(201);
            baseResp.setMgs("用户名或邮箱为空");
            return baseResp;
        }
        if(user1 == null){
            baseResp.setCode(202);
            baseResp.setMgs("用户名或邮箱不存在");
            return baseResp;
        }
        if(StringUtils.isEmpty(user.getPassword())){
            baseResp.setCode(203);
            baseResp.setMgs("密码为空");
            return baseResp;
        }
        if(!user.getPassword().equals(user1.getPassword())){
            baseResp.setCode(204);
            baseResp.setMgs("密码错误");
            return baseResp;
        }
        JwtUtils jwtUtils = new JwtUtils();
        Map map = new HashMap();
        String name = "userName";
        map.put(name, user.getName());
        String token = jwtUtils.createToken(map,name);

        baseResp.setData(token);
        baseResp.setCode(200);
        baseResp.setMgs("登录成功");
        return baseResp;
    }

    @Override
    public BaseResp del(Integer id) {
        BaseResp baseResp = new BaseResp();
        if (id!=null){
            userMapper.del(id);
            baseResp.setMgs("删除成功");
            baseResp.setCode(200);
            return baseResp;
        }
        baseResp.setCode(203);
        baseResp.setMgs("删除失败");
        return baseResp;
    }

    @Override
    public BaseResp updatepassword(UserReq userReq, HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        HttpSession session = request.getSession();
        Object object = session.getAttribute("updateemail");
        if(object == null){
            baseResp.setCode(206);
            baseResp.setMgs("验证码为空");
            return baseResp;
        }
        if(!object.equals(userReq.getCode())){
            baseResp.setCode(207);
            baseResp.setMgs("验证码错误");
            return baseResp;
        }
        User user = new User();
        //把userReq的值赋给user
        BeanUtils.copyProperties(userReq,user);
        //加密接口
        String jiami = MyJia.jiami(user.getPassword());

        user.setPassword(jiami);

        int update = userMapper.update(user);
        if (update==1){
            baseResp.setMgs("修改密码成功");
            baseResp.setCode(200);
            return baseResp;
        }
        baseResp.setCode(203);
        baseResp.setMgs("修改密码失败");
        return baseResp;
    }

    @Override
    public BaseResp findOne(Integer id) {
        BaseResp baseResp = new BaseResp();
        if (id!=null){
            User one = userMapper.findOne(id);
            baseResp.setData(one);
            return baseResp;
        }
        baseResp.setMgs("查无此人");
        return baseResp;
    }

    @Override
    public BaseResp update(User user) {
        BaseResp baseResp = new BaseResp();
        int update = userMapper.update(user);
        if (update==1){
            baseResp.setMgs("修改成功");
            baseResp.setCode(200);
            return baseResp;
        }
        baseResp.setMgs("修改失败");
        baseResp.setCode(203);
        return baseResp;
    }

    @Override
    public BaseResp getUser(String name) {
        BaseResp baseResp = new BaseResp();
        User byName = userRepository.findByName(name);
        System.out.println("======="+byName.toString());
        baseResp.setCode(200);
        baseResp.setData(byName);
        return baseResp;
    }

    @Override
    public BaseResp findphone(String phone ,String code) {
        BaseResp baseResp = new BaseResp();
        User findphone = userMapper.findphone(phone);

        if (findphone== null) {
            baseResp.setCode(123);
            baseResp.setMgs("该手机没有注册");
            return baseResp;
        }else {
            Boolean select = sendPhone.select(phone, code);
            if (select) {
                JwtUtils jwtUtils = new JwtUtils();
                Map map = new HashMap();
                String name = "userName";
                map.put(name, findphone.getName());
                String token = jwtUtils.createToken(map, name);
                baseResp.setData(token);
                baseResp.setCode(200);
                
                baseResp.setMgs(findphone.getName());
                return baseResp;
            } else {
                baseResp.setCode(20022);
                baseResp.setMgs("登录失败");
                return baseResp;
            }
        }
    }
}
